#include "frame.h"
#include "serial.h"
#include "video.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <poll.h>

extern int serial_fd;

extern int send_frame(uint8_t command, const uint8_t *data, uint16_t length);

extern int video_init(const char *device);
extern void video_cleanup();
extern int video_capture_frame(VideoFrame *frame);
extern uint32_t compress_frame(const VideoFrame *src, uint8_t *dest);

void handle_user_input() {
    char input[256];
    printf("\nPlease enter command: \n");
    printf("1. Send data\n");
    printf("2. Send file\n");
    printf("3. Exit\n");
    printf("4. Send real-time video\n");
    
    fgets(input, sizeof(input), stdin);
    
    switch(atoi(input)) {
        case 4: {
            printf("Starting video capture...\n");
            if(video_init("/dev/video0") == 0) {
                printf("Video capture started, press any key to stop\n");
                VideoFrame frame;
                uint8_t compressed_buffer[VIDEO_CHUNK_SIZE];
                
                send_frame(CMD_VIDEO_START, NULL, 0);
                
                struct pollfd pfd = {.fd = STDIN_FILENO, .events = POLLIN};
                while (poll(&pfd, 1, 100) == 0) {
                    if(video_capture_frame(&frame) == 0) {
                        uint32_t compressed_size = compress_frame(&frame, compressed_buffer);
                        send_frame(CMD_VIDEO_FRAME, compressed_buffer, compressed_size);
                        usleep(5000);
                    }
                    if (pfd.revents & POLLIN) break;
                }
                getchar();
                send_frame(CMD_VIDEO_END, NULL, 0);
                video_cleanup();
            }
            break;
        }
        case 1: {
            printf("Please enter data to send: ");
            fgets(input, sizeof(input), stdin);
            input[strcspn(input, "\n")] = 0;
            send_frame(CMD_DATA, (uint8_t*)input, strlen(input));
            break;
        }
        case 2: {
            printf("Please enter file path: ");
            fgets(input, sizeof(input), stdin);
            input[strcspn(input, "\n")] = 0;
            
            FILE *file = fopen(input, "rb");
            if (!file) {
                perror("Failed to open file");
                break;
            }
            
            send_frame(CMD_FILE_START, (uint8_t*)input, strlen(input));
            
            uint8_t buffer[FILE_CHUNK_SIZE];
            size_t bytes_read;
            while ((bytes_read = fread(buffer, 1, FILE_CHUNK_SIZE, file)) > 0) {
                send_frame(CMD_FILE_CHUNK, buffer, bytes_read);
                usleep(10000);
            }
            
            send_frame(CMD_FILE_END, NULL, 0);
            fclose(file);
            break;
        }
        case 3:
            exit(0);
        default:
            printf("Invalid command\n");
    }
}